package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>
        implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fastdfs.url}")
    private String fastServiceUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        String fileId;
        try {
            fileId = fastDFSClient.uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_FAIL);
        }
        WmMaterial wmMaterial = new WmMaterial();
        WmUser wmUser = WmThreadLocalUtils.getUser();
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        boolean saveResult = this.save(wmMaterial);
        if (!saveResult) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SAVE_FAIL);
        }
        wmMaterial.setUrl(fastServiceUrl + fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1.参数校验
        dto.checkParam();
        // 2.根据isCollection进行查询
        LambdaQueryWrapper<WmMaterial> wmMaterialLambdaQueryWrapper = Wrappers.<WmMaterial>lambdaQuery();

        if (dto != null && dto.getIsCollection() != null && dto.getIsCollection().shortValue() == 1) {
            // 查询收藏的
            wmMaterialLambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 3.根据当前登录用户进行查询
        Integer userId = WmThreadLocalUtils.getUser().getId();
        wmMaterialLambdaQueryWrapper.eq(WmMaterial::getUserId, userId);
        // 4.根据时间进行倒序查询返回
        wmMaterialLambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 5.调用api进行列表查询
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage pageResult = page(page, wmMaterialLambdaQueryWrapper);
        ResponseResult pageResponseResult =
                new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        // 6.给每个素材拼接上url  fastServiceUrl
        List<WmMaterial> wmMaterialList = pageResult.getRecords();
        List<WmMaterial> newWmMaterialList = wmMaterialList.stream().map(item -> {
            item.setUrl(fastServiceUrl + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        // 7.返回ResponseResult
        pageResponseResult.setData(newWmMaterialList);
        return pageResponseResult;
    }

    @Override
    public ResponseResult delWmMaterial(Integer id) {
        // 1.参数校验
        if (null == id) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2.根据id查询数据
        WmMaterial wmMaterial = getById(id);
        if (null == wmMaterial) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3.查询图片是否被引用，如果被引用了，不能进行删除
        LambdaQueryWrapper<WmNewsMaterial> wmNewsMaterialWrapper =
                Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id);
        Integer wmNewsMaterialCount = wmNewsMaterialMapper.selectCount(wmNewsMaterialWrapper);
        if (wmNewsMaterialCount > 0) {
            return ResponseResult.errorResult(500, "被引用的素材不能删除");
        }
        // 4.执行删除的api
        boolean removeResult = removeById(id);
        if (!removeResult) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FAIL);
        }
        // 5.删除fastDFS上的图片文件
        String fileId = wmMaterial.getUrl().replace(fastServiceUrl, "");
        try {
            fastDFSClient.delFile(fileId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FAIL, "fastDFS上的文件删除失败");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult collect(Integer id, Short isCollection) {
        if (null == id) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // update wm_material set is_collection = #{isCollection} where id = #{id}
        LambdaUpdateWrapper<WmMaterial> wmMaterialWrapper = Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, isCollection).eq(WmMaterial::getId, id);
        boolean updateResult = update(wmMaterialWrapper);
        if (!updateResult) {
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_FAIL);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
